﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CVSA.Suporte.Sinacor.BMFBovespa.Negocio;
using CVSA.Suporte.Sinacor.BMFBovespa.Entidades;
using System.Configuration;
using System.Data;

namespace CVSA.Suporte.Sinacor.BMFBovespa.ConsultaRemedy
{
    public partial class DesempenhoEquipe : System.Web.UI.Page
    {
        private Remedy remedy = new Remedy();
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ddlPeriodo.DataSource = remedy.getPeriodos();
                ddlPeriodo.DataTextField = "DataFechamento";
                ddlPeriodo.DataValueField = "DataFechamento";
                ddlPeriodo.DataBind();
                string dtInicio = "01/" + ddlPeriodo.SelectedValue;
                DateTime dtFinal = Convert.ToDateTime(dtInicio).AddMonths(1).AddDays(-1);
                BindGrid(dtInicio, dtFinal);
            }
        }

        protected void ddlPeriodo_SelectedIndexChanged(object sender, EventArgs e)
        {
            string dtInicio = "01/" + ddlPeriodo.SelectedValue;
            DateTime dtFinal = Convert.ToDateTime(dtInicio).AddMonths(1).AddDays(-1);
            BindGrid(dtInicio, dtFinal);
            
        }

        public DataTable PivotTable(DataTable source)
        {
            DataTable dest = new DataTable("Pivoted" + source.TableName);

            // create shchema (string columns) for the destination
            // the first column is for the source column name
            dest.Columns.Add(" ");

            // the remaining dest columns are from each source table row (1st column)
            DataRow r = null;
            foreach (DataRow r_loopVariable in source.Rows)
            {
                r = r_loopVariable;
                dest.Columns.Add(r[0].ToString());
            }

            // now add one row to the dest table for each column in the source, except
            // the first which is the Product, in our case
            int i = 0;
            for (i = 0; i <= source.Columns.Count - 1 - 1; i += i + 1)
            {
                dest.Rows.Add(dest.NewRow());
            }

            // now move the source columns to their position in the dest row/cell matrix
            // starting down the destination rows, and across the columns
            int rr = 0;
            int c = 0;
            for (rr = 0; rr <= dest.Rows.Count - 1; rr += rr + 1)
            {
                for (c = 0; c <= dest.Columns.Count - 1; c += c + 1)
                {
                    if (c == 0)
                    {
                        dest.Rows[rr][0] = source.Columns[rr + 1].ColumnName;
                        // the Product name
                    }
                    else
                    {
                        dest.Rows[rr][c] = source.Rows[c - 1][rr + 1];
                    }
                }
                c = 0;
            }
            dest.AcceptChanges();
            return dest;
        }

        public DataTable CrossTab(DataTable dtS, string leftColumn, string topField, string dataValue, string pFix)
        {

            if (dtS == null)
            {
                return null;
            }

            DataTable dtOut = new DataTable();
            DataTable dtRowTitle = new DataTable();
            DataTable dtColHeader = new DataTable();

            dtRowTitle = dtS.DefaultView.ToTable(true, dtS.Columns[leftColumn].ColumnName);
            dtColHeader = dtS.DefaultView.ToTable(true, dtS.Columns[topField].ColumnName);

            DataColumn dColx = new DataColumn();
            dColx.ColumnName = leftColumn;
            dColx.Caption = leftColumn;
            dtOut.Columns.Add(dColx);

            foreach (DataRow drow in dtColHeader.Rows)
            {
                DataColumn dCol = new DataColumn();
                dCol.ColumnName = pFix + drow[topField].ToString().Trim();
                dtOut.Columns.Add(dCol);
            }

            DataRow drowx = null;

            foreach (DataRow drow in dtRowTitle.Rows)
            {
                drowx = dtOut.NewRow();
                drowx[0] = drow[leftColumn].ToString();
                dtOut.Rows.Add(drowx);
            }


            Int32 xVal = 0;
            Int32 yVal = 0;

            foreach (DataRow mRow in dtS.Rows)
            {
                string xRowVal = mRow[leftColumn].ToString();
                string dataVal = mRow[dataValue].ToString();
                string yColVal = mRow[topField].ToString().Trim();

                foreach (DataRow nRow in dtOut.Rows)
                {
                    if (xRowVal == nRow[0].ToString())
                    {
                        for (xVal = 0; xVal <= nRow.Table.Columns.Count - 1; xVal++)
                        {
                            if (nRow.Table.Columns[xVal].ColumnName == pFix + yColVal)
                            {
                                Int32 rIndex = dtOut.Rows.IndexOf(nRow);
                                dtOut.Rows[rIndex][xVal] = dataVal;

                                break; // TODO: might not be correct. Was : Exit For
                            }
                        }
                        break; // TODO: might not be correct. Was : Exit For
                    }
                }
            }

            dtOut.DefaultView.Sort = dtOut.Columns[0].ColumnName;
            return dtOut;
        }

        private void BindGrid(string dtInicio, DateTime dtFinal)
        {
            DataTable odv = CrossTab(remedy.getChamadosForcatarefa(dtInicio, dtFinal.ToString("dd/MM/yyyy")), "DIA", "PESSOA_DESIGNADA", "QTD_FEC", "");
            foreach (DataRow rv in odv.Rows)
            {
                rv[0] = Convert.ToDateTime(rv[0]).ToString("dd/MM/yyyy");
            }
            odv.Columns.Add("Total");
            pivot.DataSource = odv;
            pivot.DataBind();

           for (int r = 0; r <= pivot.Rows.Count - 1; r++)
            {
                int subtotalcolunas = 0;
                for (int i = 1; i <= odv.Columns.Count -1; i++)
                {
                    int valor = 0;
                    int.TryParse(pivot.Rows[r].Cells[i].Text.ToString(), out valor);
                    subtotalcolunas += valor;
                }
                pivot.Rows[r].Cells[odv.Columns.Count - 1].Text = subtotalcolunas.ToString();
            }
            
            int total = 0;

            DataView  odvTotais  = new DataView(odv);
            odvTotais.Table.Rows.Clear();
            
            DataRow newrow;
            newrow = odvTotais.Table.NewRow();
            odvTotais.Table.Rows.Add(newrow);
            odvTotais.Table.Columns.RemoveAt(0);
            
            
            gvtotais.DataSource = odvTotais;
            gvtotais.DataBind();

            for (int i = 1; i <= odv.Columns.Count -1 ; i++)
            {
                int subtotal = 0;
                for (int r = 0; r <= pivot.Rows.Count - 1; r++)
                {
                    int valor = 0;
                    int.TryParse(pivot.Rows[r].Cells[i].Text.ToString(), out valor);
                    subtotal += valor;
                    gvtotais.Rows[0].Cells[i -1].Text = subtotal.ToString();
                }
                total += subtotal;
            }
            gvtotais.Rows[0].Cells[odvTotais.Table.Columns.Count - 1].Text = total.ToString();
            lblTot.Text = total.ToString();
        }
        
    }
}